package com.springboot2.shiro.mgt.realm;

import com.springboot2.shiro.data.enity.User;
import com.springboot2.shiro.data.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * ShiroJdbcRealm
 *
 * @author Archx[archx@foxmail.com]
 * at 2018/7/13 21:40
 */
public class ShiroJdbcRealm extends AuthorizingRealm {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String      login       = (String) principals.getPrimaryPrincipal();
        Set<String> permissions = userService.getPermissionsByLogin(login);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String login = (String) token.getPrincipal();
        User   user  = userService.getRepository().findByUsernameEquals(login);

        if (user == null) {
            throw new UnknownAccountException();
        }

        if (user.getState() != User.State.Enabled) {
            throw new LockedAccountException();
        }

        return new SimpleAuthenticationInfo(login, user.getPassword(), getName());
    }

    @Override
    protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
        return principals.getPrimaryPrincipal();
    }
}
